package pri.damai.xiaowu.common.log.config;

import pri.damai.xiaowu.common.core.filter.ThreadLocalUserFilter;
import pri.damai.xiaowu.common.log.FilterProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;

/**
 *
 * @Desc
 * @Author DaMai
 * @Date 2021/5/19 16:12
 * 但行好事，莫问前程。
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "xiaowu.filter.local-user-enable", havingValue = "true")
public class ThreadLocalUserFilterConfig {

    @Bean
    @ConditionalOnMissingBean
    public FilterProperties filterProperties() {
        return new FilterProperties();
    }

    @Bean
    public FilterRegistrationBean<ThreadLocalUserFilter> threadLocalUserFilter() {

        if (StringUtils.isBlank(filterProperties().getUrlPattern())) {
            throw new RuntimeException("未配置 Filter 拦截 UrlPattern。");
        }

        FilterRegistrationBean<ThreadLocalUserFilter> filter = new FilterRegistrationBean<>();
        filter.setName(ThreadLocalUserFilter.FILTER_NAME);
        filter.setFilter(new ThreadLocalUserFilter());
        filter.setUrlPatterns(Collections.singletonList(filterProperties().getUrlPattern()));

        log.info("【Xiao Wu】ThreadLocalUserFilter 配置成功。");

        return filter;
    }
}
